package com.share.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.domain.SecurityUser;
import com.share.mapper.SysPermissionsMapper;
import com.share.mapper.SysRoleMapper;
import com.share.service.ISysUserService;
import com.share.user.admin.pojos.SysPermissions;
import com.share.user.admin.pojos.SysRole;
import com.share.user.admin.pojos.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Security用户配置
 */
@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    private final ISysUserService sysUserService;
    private final SysRoleMapper sysRoleMapper;
    private final SysPermissionsMapper sysPermissionsMapper;

    public UserDetailServiceImpl(ISysUserService sysUserService, SysRoleMapper sysRoleMapper, SysPermissionsMapper sysPermissionsMapper) {
        this.sysUserService = sysUserService;
        this.sysRoleMapper = sysRoleMapper;
        this.sysPermissionsMapper = sysPermissionsMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(!StringUtils.hasLength(username)){
            throw new UsernameNotFoundException("用户名为空");
        }
        LambdaQueryWrapper<SysUser> queryWrapper =
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername,username);
        SysUser sysUser = sysUserService.getOne(queryWrapper);
        if(Objects.isNull(sysUser)){
            throw new UsernameNotFoundException("用户名或者密码错误");
        }
        //查询用户角色
        List<SysRole> sysRolesList = sysRoleMapper.SelectRoleINPermissionsByUserId(sysUser.getId());
        Optional<List<SysRole>> optionalRole = Optional.ofNullable(sysRolesList);
        //转换数组
        List<String> RoleList = optionalRole.map(roles -> roles.stream()
                        .map(SysRole::getRoleKey)
                        .map(String::new)
                        .collect(Collectors.toList()))
                .orElseGet(ArrayList::new);

        //查询用户权限
        List<SysPermissions> sysPermissionsList = sysPermissionsMapper.SelectPermissionsByUserId(sysUser.getId());
        //使用Optional进行流处理
        Optional<List<SysPermissions>> optionalPermissions = Optional.ofNullable(sysPermissionsList);
        //转换数组
        List<SimpleGrantedAuthority> authorities = optionalPermissions.map(permissions -> permissions.stream()
                        .map(SysPermissions::getPermissionKey)
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toList()))
                .orElseGet(ArrayList::new);


        return SecurityUser
                .builder()
                .id(sysUser.getId())
                .username(sysUser.getUsername())
                .password(sysUser.getPassword())
                .avatar(sysUser.getAvatar())
                .nickname(sysUser.getNickname())
                .accountNonLocked(sysUser.getAccountNonLocked())
                .accountNonExpired(sysUser.getAccountNonExpired())
                .credentialsNonExpired(sysUser.getCredentialsNonExpired())
                .enabled(sysUser.getEnabled())
                .roles(RoleList)
                .authorities(authorities)
                .build();
    }
}
